// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.unit.ula;

import com.dustedpixels.jasmin.unit.Unit;
import com.dustedpixels.jasmin.unit.tools.Oscilloscope;
import com.dustedpixels.jasmin.unit.tools.Pin;
import com.dustedpixels.jasmin.video.NullVideoOutput;
import com.dustedpixels.jasmin.video.VideoOutput;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class IRQGenerator implements Unit {
  // (input) clock source (3.5MHz)
  public boolean CLOCK;

  // (output) interrupt request
  public boolean IRQ = false;
  
  private final static int FULL_CYCLES = 69888;
  private final static int IRQ_CYCLES = 32;
  private int cycleCounter = 0;
  
  private boolean lastClock = false;
    
  public void updateEndPoints() {
    if (lastClock != CLOCK) {
      if (CLOCK) {
        if (cycleCounter == 0) {
          IRQ = true;
        } else if (cycleCounter == IRQ_CYCLES) {
          IRQ = false;
        }
        if (++cycleCounter == FULL_CYCLES) cycleCounter = 0;
      }

      lastClock = CLOCK;
    }
  }
  
  
  public static void main(String[] args) {
    IRQGenerator irqGen = new IRQGenerator();
    
    Oscilloscope oscilloscope = new Oscilloscope(
        Pin.of("CLOCK", irqGen, "CLOCK"),
        Pin.of("IRQ", irqGen, "IRQ")
    );
    
    for (int i = 0; i < 100; i++) {
      irqGen.CLOCK = !irqGen.CLOCK;
      irqGen.updateEndPoints();
      oscilloscope.sample();
    }
    
    oscilloscope.print(8);
  }
}
